package com.ruoyi.wl.service.impl;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.wl.domain.WlArea;
import com.ruoyi.wl.domain.WlCompany;
import com.ruoyi.wl.domain.WlOrder;
import com.ruoyi.wl.mapper.WlAreaMapper;
import com.ruoyi.wl.mapper.WlCompanyMapper;
import com.ruoyi.wl.mapper.WlOrderMapper;
import com.ruoyi.wl.service.IWlOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 订单管理Service业务层处理
 *
 * @author zhiminhu
 * @date 2021-06-25
 */
@Service
public class WlOrderServiceImpl implements IWlOrderService {
    private static final Logger log = LoggerFactory.getLogger(WlOrderServiceImpl.class);

    @Autowired
    private WlOrderMapper wlOrderMapper;
    @Autowired
    private WlAreaMapper wlAreaMapper;
    @Autowired
    private WlCompanyMapper wlCompanyMapper;
    @Autowired
    private SysUserMapper sysUserMapper;



    /**
     * 查询订单管理
     *
     * @param id 订单管理ID
     * @return 订单管理
     */
    @Override
    public WlOrder selectWlOrderById(Long id) {
        return wlOrderMapper.selectWlOrderById(id);
    }

    @Override
    public WlOrder selectWlOrderByOrderNum(String orderNum) {
        return wlOrderMapper.selectWlOrderByOrderNum(orderNum);
    }

    @Override
    public WlOrder selectWlOrderByNu(String nu) {
        return wlOrderMapper.selectWlOrderByNu(nu);
    }

    /**
     * 查询订单管理列表
     *
     * @param wlOrder 订单管理
     * @return 订单管理
     */
    @Override
    public List<WlOrder> selectWlOrderList(WlOrder wlOrder) {
        return wlOrderMapper.selectWlOrderList(wlOrder);
    }

    /**
     * 新增订单管理
     *
     * @param wlOrder 订单管理
     * @return 结果
     */
    @Override
    public int insertWlOrder(WlOrder wlOrder) {
        wlOrder.setCreateTime(DateUtils.getNowDate());
        return wlOrderMapper.insertWlOrder(wlOrder);
    }

    /**
     * 修改订单管理
     *
     * @param wlOrder 订单管理
     * @return 结果
     */
    @Override
    public int updateWlOrder(WlOrder wlOrder) {
        wlOrder.setUpdateTime(DateUtils.getNowDate());
        return wlOrderMapper.updateWlOrder(wlOrder);
    }

    /***
     * 更新订单的物流信息
     * @param order
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateWlOrderExpress(WlOrder order) {


        return 1;
    }

    /**
     * 删除订单管理对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteWlOrderByIds(String ids) {
        return wlOrderMapper.deleteWlOrderByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除订单管理信息
     *
     * @param id 订单管理ID
     * @return 结果
     */
    @Override
    public int deleteWlOrderById(Long id) {
        return wlOrderMapper.deleteWlOrderById(id);
    }

    /**
     * 导入订单数据
     *
     * @param orderList       用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importOrder(List<WlOrder> orderList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(orderList) || orderList.size() == 0) {
            throw new BusinessException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (WlOrder order : orderList) {
            try {
                // 验证是否存在这个订单
                WlOrder orderE = wlOrderMapper.selectWlOrderByOrderNum(order.getOrderNum());
                if (StringUtils.isNull(orderE)) {
                    order.setCreateBy(operName);
                    //设置区域信息
                    List<WlArea> areas = wlAreaMapper.selectWlAreaList(new WlArea(order.getAreaName()));
                    WlArea area = new WlArea();
                    if (areas.size() > 0) {
                        area = areas.get(0);
                        order.setAreaId(area.getAreaId());
                    } else {
                        area.setAreaName(order.getAreaName());
                        area.setStatus("0");
                        wlAreaMapper.insertWlArea(area);
                        order.setAreaId(area.getAreaId());
                    }
                    //设置客户信息
                    List<WlCompany> companies = wlCompanyMapper.selectWlCompanyList(new WlCompany(order.getCompanyName()));
                    WlCompany company = new WlCompany();
                    if (companies.size() > 0) {
                        company = companies.get(0);
                        order.setCompanyKey(company.getCompanyKey());
                    } else {
                        company.setCompanyName(order.getCompanyName());
                        company.setCompanyKey(order.getCompanyName());
                        company.setStatus("0");
                        wlCompanyMapper.insertWlCompany(company);
                        order.setCompanyKey(company.getCompanyKey());
                    }
                    //设置销售信息
                    if (UserConstants.USER_NAME_NOT_UNIQUE.equals(sysUserMapper.checkLoginNameUnique(order.getSalesmenName()))) {
                        SysUser user = sysUserMapper.selectUserByLoginName(order.getSalesmenName());
                        order.setSalesmenId(user.getUserId());
                    }
                    if(StringUtils.isNotEmpty(order.getRecPhone())) {
                        this.insertWlOrder(order);
                        successNum++;
                        successMsg.append("<br/>" + successNum + "、订单 [" + order.getOrderNum() + "] 导入成功");
                    }else {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、订单 [" + order.getOrderNum() + "] 收件人手机不能为空");
                    }
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、订单 [" + order.getOrderNum() + "] 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、订单[ " + order.getOrderNum() + "] 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
